//
//  FMDBManager.m
//  ProjectA
//
//  Created by 邹浩 on 15/10/8.
//  Copyright (c) 2015年 蓝鸥. All rights reserved.
//

#import "FMDBManager.h"
#import <objc/runtime.h>

@interface FMDBManager ()

@property (nonatomic, strong)FMDatabase *db;

@end

@implementation FMDBManager

- (instancetype)init{
    if (self = [super init]){
        //创建管理对象时关联数据库
        [self creatTheSQL];
    }
    return self;
}

- (void)creatTheSQL
{
    NSString* docsdir = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString* dbpath = [docsdir stringByAppendingPathComponent:@"user.sqlite"];
    self.db = [FMDatabase databaseWithPath:dbpath];
     
}
//直接传进来你要存的对象，不要传字典，只是model
- (BOOL)instertTheData:(id)model
{
    //获取对象的类名
    NSString *name = NSStringFromClass([model class]);
    //下面都是拼接sql语句的操作
    NSMutableString *sql = [NSMutableString stringWithFormat:@"INSERT INTO %@ (", name];
    //声明一个非负整形变量，用与接收model里面有多少个属性
    u_int count;
    //获取model的属性列表指针数组
    objc_property_t *properties  =class_copyPropertyList([model class], &count);
    NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i<count; i++)
    {
        //根据属性指针数组对应的下标获取属性名，为一个char指针，runtime是一个C语言底层库，所以函数返回值应为C里面的变量或者指针，这个应该可以理解
        const char* propertyName =property_getName(properties[i]);
        //将char指针转为字符串，添加到数组中，添加到数组里面的及为属性名，
        [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
    }
    //所有属性名拿到之后，释放掉属性指针
    free(properties);
    //将属性名添加到SQL语句中，拼接成一个完整的sql语句
    for (int i = 0; i < count ; i++) {

        [sql appendString:propertiesArray[i]];
        [sql appendString:@","];
        
    }
    [sql deleteCharactersInRange:NSMakeRange(sql.length-1, 1)];
    [sql appendString:@") VALUES ("];
    for (int i = 0; i<count; i++) {
        NSString *string;
//        NSLog(@"%@", [[model valueForKey:propertiesArray[i]] class]);
        //当存入对象的某些属性为空时,及值为null，无法判断属性的类型，这点有待完善，个人认为可能还是要用到runtime来获取属性的类型，等待大家一起完善，判断类型只要是字符串类型和其他类型不一样在sql语句中，字符串需要用‘’或者“”包裹
        if ([[model valueForKey:propertiesArray[i]] isKindOfClass:[NSString class]]) {

                string = [NSString stringWithFormat:@"'%@',", [model valueForKey:propertiesArray[i]]];
            
        } else {
            string = [NSString stringWithFormat:@"%@,", [model valueForKey:propertiesArray[i]]];
        }
        
        [sql appendString:string];

    }
    [sql deleteCharactersInRange:NSMakeRange(sql.length-1, 1)];
    [sql appendString:@");"];
    [self.db open];
//    if ([self.db executeUpdate:[self returnTheSqlWithCreatTable:model]]) {
//    
//    }
    //创建表
    NSString *sqlStr = [self returnTheSqlWithCreatTable:model];
    [self.db executeUpdate:sqlStr];
//    NSLog(@"%@", sql);
//    NSLog(@"%d", );
//    [self creatTheSQL];
//    [self.db executeUpdate:sql];
//    [self.db close];
//    self.db
    //插入数据
    return [self.db executeUpdate:sql];
}
//取数据
- (NSArray *)searchTheDataWithForm:(NSString *)formName
{
    NSString *selectStr = [NSString stringWithFormat:@"select * from %@", formName];
    FMResultSet *rs = [self.db executeQuery:selectStr];
    Class modelName = NSClassFromString(formName);
    u_int count;
    objc_property_t *properties  =class_copyPropertyList([modelName class], &count);
    NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i<count; i++)
    {
        const char* propertyName =property_getName(properties[i]);
        [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
    }
    free(properties);
    NSMutableArray *array = [NSMutableArray array];
    while ([rs next]) {
        id model = [[modelName alloc] init];
        for (NSString *str in propertiesArray) {
            [model setValue:[rs stringForColumn:@"firstname"] forKey:str];
        }
        [array addObject:model];
    }
    [self.db close];
    return array;
}

- (NSString *)returnTheSqlWithCreatTable:(id)model
{
    //4.创表
//    [self creatTheSQL];
    NSMutableString *sql = [NSMutableString stringWithFormat:@"CREATE TABLE IF NOT EXICTS %@ (", NSStringFromClass([model class])];
    
    u_int count;
    objc_property_t *properties  =class_copyPropertyList([model class], &count);
    NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i<count; i++)
    {
        const char* propertyName =property_getName(properties[i]);
        [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
    }
    free(properties);

    for (int i = 0; i < count; i++) {
        if ([[model valueForKey:propertiesArray[i]] isKindOfClass:[NSString class]]) {
            NSString *str = [NSString stringWithFormat:@"%@ text NOT NULL,", propertiesArray[i]];
            [sql appendString:str];
        } else {
            NSString *str = [NSString stringWithFormat:@"%@ integer NOT NULL,", propertiesArray[i]];
            [sql appendString:str];
        }
    }
    [sql deleteCharactersInRange:NSMakeRange(sql.length-1, 1)];
    [sql appendString:@");"];
    

    return sql;
}



@end
